//
//  ChatViewController.m
//  uniquelove
//
//  Created by ibokan on 14-12-15.
//  Copyright (c) 2014年 ibokan. All rights reserved.
//

#import "ChatViewController.h"
#import "Message.h"
#import "MessageCell.h"
#import "MessageFrame.h"

@interface ChatViewController ()
@property (strong, nonatomic) XMPPStream *stream;
@property (strong, nonatomic) IBOutlet UITextField *textField;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
- (IBAction)sendBtnPressed:(id)sender;

@property (strong, nonatomic) NSMutableArray *messagesArray;
@property (strong, nonatomic) NSMutableArray *tempArray;
@end

@implementation ChatViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.messagesArray = [NSMutableArray arrayWithCapacity:100];
    self.tempArray = [NSMutableArray arrayWithCapacity:100];
    
    //设置XMPPStream的stream对象
    UIApplication *app = [UIApplication sharedApplication];
    id delegate = [app delegate];
    self.stream = [delegate stream];
    //设置XMPP代理
    [self.stream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    [self setUserJid];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // 表格的设置
    // 去除分割线
    self.tableView.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.allowsSelection = NO; // 不允许选中
    
    
    
    // 监听键盘的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
}

/**
 *  当键盘改变了frame(位置和尺寸)的时候调用
 */
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
    // 设置窗口的颜色
    self.view.window.backgroundColor = self.tableView.backgroundColor;
    
    // 0.取出键盘动画的时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 1.取得键盘最后的frame
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 2.计算控制器的view需要平移的距离
    CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
    
    // 3.执行动画
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, transformY);
    }];
}

-(BOOL)prefersStatusBarHidden{   //隐藏状态栏
    return YES;
}

/**
 *  当开始拖拽表格的时候就会调用
 */
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 退出键盘
    [self.view endEditing:YES];
}

//-(NSMutableArray *)getMessageModel:(NSDictionary *)dict{
//    NSMutableArray *mutArray = [NSMutableArray array];
//    NSArray *array = dict[@"result"];
//    for (NSDictionary *dic in array) {
//        NSString *text = dic[@"state"][@"content"];
//        NSString *time = dic[@"state"][@"date"];
//        NSString *fromUid = dic[@"state"][@"fromUid"];
//        NSNumber *type;
//        if ([fromUid isEqualToString:@"1956859800"]) {  //自己
//            type = @0;
//        }else{
//            type = @1;
//        }
//        
//        NSDictionary *addDict = @{@"text": text,@"time":time,@"type":type};
//        [mutArray addObject:addDict];
//    }
//    
//    return mutArray;
//}




-(void)setUserJid{
    NSString *userJid = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    XMPPJID *jid = [XMPPJID jidWithUser:userJid domain:@"developer.bjbkws.com" resource:@"chat"];
    //将jid与stram进行关联
    [self.stream setMyJID:jid];
    //用此jid链接服务器
    NSError *error;
    if (![self.stream connectWithTimeout:20 error:&error]) {
        NSLog(@"error = %@",[error localizedDescription]);
    };
}

-(void)xmppStreamDidConnect:(XMPPStream *)sender{
    //链接成功后，为此jid设置密码或者登录
    NSLog(@"jid链接成功");
    NSError *error;
    NSString *userJid = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSLog(@"%@",userJid);
    [self.stream registerWithPassword:userJid error:&error];
}

- (void)xmppStreamDidRegister:(XMPPStream *)sender{
    NSError *error;
    NSLog(@"------xmppStreamDidRegister");
    NSString *userJid = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    [self.stream authenticateWithPassword:userJid error:&error];
}

- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error{
    
    NSError *error1;
    NSLog(@"------xmppStreamDidRegister");
    NSString *userJid = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    [self.stream authenticateWithPassword:userJid error:&error1];
}

-(void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error{
    NSLog(@"%@",error);
}
//根据jid链接服务器失败
- (void)xmppStreamConnectDidTimeout:(XMPPStream *)sender{
    NSLog(@"xmppStreamConnectDidTimeout");
}
//根据jid链接服务器成功并成功验证密码之后（登录后）
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
    
    NSLog(@"登录成功");
    //上线状态
    XMPPPresence *presence = [XMPPPresence presence];
    
    [self.stream sendElement:presence];
}
//登录验证失败
-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(id)error{
    NSLog(@"didNotAuthenticate");
}

//发送消息
- (IBAction)sendBtnPressed:(id)sender {
    NSString *userJid = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
//    NSString *userJid = @"666666";
    XMPPJID *jid = [XMPPJID jidWithUser:userJid domain:@"developer.bjbkws.com" resource:@"chat"];
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:jid];
    [message addBody:self.textField.text];
     NSLog(@"%@",message);
    [self.stream sendElement:message];
    self.textField.text = nil;
    
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd  HH:mm";
    //添加模型数据
    //time
    Message *msg = [Message new];
    msg.text = message.body;
    msg.type = MessageTypeMe;
    msg.time = [formatter stringFromDate:date];
    //看是否需要显示时间
    //    if (self.messagesArray.count != 0) {
    MessageFrame *lastMF = [self.messagesArray lastObject];
    Message *lastMSG = lastMF.message;
    msg.hideTime = [msg.time isEqualToString:lastMSG.time];
    //    }else{
    //        msg.hideTime = NO;
    //    }
    
    //frame模型
    MessageFrame *mf = [MessageFrame new];
    mf.message = msg;
    [self.messagesArray addObject:mf];
    
    [self.tableView reloadData];
#warning 看情况进行修改
    // 退出键盘
//    [self.view endEditing:YES];
    
    // 4.自动滚动表格到最后一行
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:self.messagesArray.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

    
}

//收到信息
-(void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message{
    
    NSLog(@"from = %@",message.fromStr);
    NSLog(@"text = %@",message.body);
//    [self.messagesArray addObject:message];
    NSLog(@"%@",message);
    NSDate *date = [NSDate date];
    NSLog(@"%@",date);
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd  HH:mm";
    //添加模型数据
    //time
    Message *msg = [Message new];
    msg.text = message.body;
    msg.type = MessageTypeOther;
    msg.time = [formatter stringFromDate:date];
    //看是否需要显示时间
    NSLog(@"%d",self.messagesArray.count);
    NSLog(@"%@",self.messagesArray);
    if (self.messagesArray.count != 0) {
        MessageFrame *lastMF = [self.messagesArray lastObject];
        Message *lastMSG = lastMF.message;
        msg.hideTime = [msg.time isEqualToString:lastMSG.time];
    }else{
        msg.hideTime = NO;
    }
    
    //frame模型
    MessageFrame *mf = [MessageFrame new];
    mf.message = msg;
    [self.messagesArray addObject:mf];
    
    [self.tableView reloadData];
    
#warning 看情况进行修改
    // 退出键盘
//    [self.view endEditing:YES];
    
    
    // 4.自动滚动表格到最后一行
    NSIndexPath *lastPath = [NSIndexPath indexPathForRow:self.messagesArray.count - 1 inSection:0];
    [self.tableView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.messagesArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 1.创建cell
    MessageCell *cell = [MessageCell cellWithTableView:tableView];
    
    
    // 2.给cell传递模型
    cell.messageFrame = self.messagesArray[indexPath.row];
    
    // 3.返回cell
    return cell;
}

#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageFrame *mf = self.messagesArray[indexPath.row];
    return mf.cellHeight;
}


@end
